package com.ctg.behavior.calc.impala.builder.userlist;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.ctg.behavior.common.consts.CtFieldConsts;
import com.ctg.behavior.common.userslist.CtULCalcBody;
import com.ctg.behavior.common.userslist.CtULCalcData;
import com.ctg.behavior.common.userslist.CtULCalcResult;
import com.ctg.behavior.utils.CtDateUtils;
import com.ctg.behavior.utils.CtStringUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class CtULCalcResultBuilder {

	public CtULCalcResult doBuilder(CtULCalcResult userlistResult, List<LinkedHashMap<String, Object>> calcResult, CtULCalcBody ulCalcBody) {

		userlistResult.getValue().setAppId(ulCalcBody.getAppId());
		userlistResult.getValue().setBookmarkId(ulCalcBody.getBookmarkId());
		userlistResult.getValue().setRequestId(ulCalcBody.getRequestId());

		userlistResult.getValue().setReportUpdateTime(CtDateUtils.dateToString(new Date()));
		userlistResult.getValue().setDataUpdateTime(CtDateUtils.dateToString(new Date()));

		userlistResult.getValue().setCurrentPage(ulCalcBody.getCurrentPage());
		userlistResult.getValue().setPageSize(ulCalcBody.getPageSize());
		userlistResult.getValue().setTotal(0);

		for (LinkedHashMap<String, Object> oneRow : calcResult) {
			String deviceId = String.valueOf(oneRow.get(CtFieldConsts.FIELD_DEVICE_ID));
			if (CtStringUtils.isEmpty(deviceId)) {
				log.error("calcResult-deviceId:{}", JSON.toJSONString(oneRow));
			}
			String userId = String.valueOf(oneRow.get(CtFieldConsts.FIELD_USER_ID));
			if (CtStringUtils.isEmpty(userId)) {
				log.error("calcResult-userId:{}", JSON.toJSONString(oneRow));
			}
			CtULCalcData calcData = new CtULCalcData();
			calcData.setDeviceId(deviceId);
			calcData.setUserId(userId);
			Set<Entry<String, Object>> entries = oneRow.entrySet();
			for (Entry<String, Object> entry : entries) {
				String key = entry.getKey();
				if (key.equals(CtFieldConsts.FIELD_DEVICE_ID) || key.equals(CtFieldConsts.FIELD_USER_ID)) {
					continue;
				}
				calcData.getProfiles().put("user."+key, String.valueOf(entry.getValue()));
			}
			userlistResult.getValue().getList().add(calcData);
		}

		return userlistResult;

	}
}
